import { decrypto, encrypto } from "../common";
/** 默认缓存期限为7天 */
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

//数据存储本地
export function setLocal(key, value, expire = DEFAULT_CACHE_TIME) {
  const storageData = {
    value,
    expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
  };
  const json = encrypto(storageData);
  window.localStorage.setItem(key, json);
}

export function getLocal(key) {
  const json = localStorage.getItem(key);
  if (json) {
    let storageData = null;
    try {
      storageData = decrypto(json);
    } catch (error) {}
    if (storageData) {
      const { value, expire } = storageData;
      //   没有过期或者无过期时间
      if (expire === null || expire >= Date.now()) return value;
    }
    //执行到这里就代表出错或者过期
    removeLocal(key);
    return null;
  }
  return null;
}

//获取指定数据的过期时间
export function getLocalExpire(key) {
  const json = localStorage.getItem(key);
  if (json) {
    let storageData = null;
    try {
      storageData = decrypto(json);
    } catch (error) {}
    if (storageData) {
      const { expire } = storageData;
      return expire;
    }
    return null;
  }
  return null;
}

// 移除本地数据
export function removeLocal(key) {
  window.localStorage.removeItem(key);
}

// 清空本地数据
export function clearLocal() {
  window.localStorage.clear();
}
